package com.tianpengtech.common.pay.service;

import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.fairorder.FairOrder;
import com.tianpengtech.common.pay.weixin.WxPayParamBuilder;

public class PayService {

	
	public void savePayOrderLog(String xml_content,Map<String,String> resultMap) throws ValidateException{
		
		String sql="select * from fair_order where unique_id=? limit 1";
		Record record = Db.findFirst(sql,resultMap.get("out_trade_no"));
		if(record==null){
			String msg = "订单信息不存在";
			WxPayParamBuilder.builderMsgToWeixin(WxPayParamBuilder.RETURN_CODE_FAIL,msg);
			throw new ValidateException(msg);
		}
		String out_trade_no=record.getStr("unique_id");
		String total_fee=record.getStr("total_fee");
		if(!resultMap.get("out_trade_no").equals(out_trade_no) && !resultMap.get("total_fee").equals(total_fee)){//校验订单号
			String msg = "订单信息有误不正确";
			WxPayParamBuilder.builderMsgToWeixin(WxPayParamBuilder.RETURN_CODE_FAIL,msg);
			throw new ValidateException(msg);
		}
		if("SUCCESS".equals(resultMap.get("result_code")) && "SUCCESS".equals(resultMap.get("return_code"))){//检查签名信息
			if(record.getInt("status")==0){
				savPayOrderLog(xml_content, resultMap);
				record.set("status", 1);
				Db.update("fair_order", record);
				updateUserSalary(record);
				WxPayParamBuilder.builderMsgToWeixin(WxPayParamBuilder.RETURN_CODE_SUCCESS,WxPayParamBuilder.RETURN_MSG_SUCCESS);
			}else{
				WxPayParamBuilder.builderMsgToWeixin(WxPayParamBuilder.RETURN_CODE_SUCCESS,WxPayParamBuilder.RETURN_MSG_SUCCESS);
			}
		}else{
			WxPayParamBuilder.builderMsgToWeixin(WxPayParamBuilder.RETURN_CODE_FAIL,"接受支付接受通知失败");
		}
		
		
	}

	public  void updateUserSalary(Record record) {
		String sql;
		//检查用户帐户表中是否存在当前用户的记录信息，假如没有新建一条，假如有，则进行累加
		sql = "select * from fair_user_salary where user_id = ? limit 1";
		Record salary = Db.findFirst(sql,record.getInt(FairOrder.USER));
		if(salary==null){
			salary = new Record();
			salary.set("user_id", record.getInt(FairOrder.USER));
			salary.set("salary", record.getInt(FairOrder.TOTAL_FEE));
			Db.save("fair_user_salary", salary);
		}else{
			int userFee = salary.getInt("salary");
			userFee = userFee+record.getInt(FairOrder.TOTAL_FEE);
			salary.set("salary", userFee);
			Db.update("fair_user_salary", salary);
		}
	}

	public int  saveOrder(String xml_content,Map<String, String> resultMap,String outTradeNo,
			long userId,String total_fee,String name){
		return saveOrder(xml_content, resultMap, outTradeNo, userId, total_fee, name, 0,0);
	}
	
	public int  saveOrder(String xml_content,Map<String, String> resultMap,String outTradeNo,
			long userId,String total_fee,String name,int objId,int opt_type){
		
		String[] v = outTradeNo.split("_");
		Record payOrder= new Record();
		payOrder.set("xml_content", xml_content);
		payOrder.set("obj_id", objId);
		payOrder.set("order_desc",name);
		payOrder.set("order_no",v[0]);
		payOrder.set("user", userId);
		payOrder.set("status", 0);
		payOrder.set("opt_type",opt_type);
		payOrder.set("pay_url", resultMap.get("code_url"));
		payOrder.set("sign", resultMap.get("sign"));
		payOrder.set("trade_type", resultMap.get("trade_type"));
		payOrder.set("prepay_id", resultMap.get("prepay_id"));
		payOrder.set("total_fee", total_fee);
		payOrder.set("unique_id", outTradeNo);
		Db.save("fair_order", payOrder);
		return payOrder.getInt("id");
	}
	
	
	
	public int  salaryPay(String outTradeNo,long userId,String total_fee,String name,int objId,int opt_type){
		String[] v = outTradeNo.split("_");
		Record payOrder= new Record();
		payOrder.set("obj_id", objId);
		payOrder.set("order_desc",name);
		payOrder.set("order_no",v[0]);
		payOrder.set("user", userId);
		payOrder.set("status", 0);
		payOrder.set("opt_type",opt_type);
		payOrder.set("total_fee", total_fee);
		payOrder.set("unique_id", outTradeNo);
		payOrder.set("trade_type", FairOrder.USER_SALARY);
		Db.save("fair_order", payOrder);
		return payOrder.getInt("id");
	}
	
	private void savPayOrderLog(String xml_content, Map<String, String> resultMap) {
		Record payOrderLog= new Record();
		payOrderLog.set("xml_content", xml_content);
		payOrderLog.set("is_subscribe", resultMap.get("is_subscribe"));
		payOrderLog.set("trade_type", resultMap.get("trade_type"));
		payOrderLog.set("total_fee", resultMap.get("total_fee"));
		payOrderLog.set("out_trade_no", resultMap.get("out_trade_no").split("_")[0]);
		payOrderLog.set("time_end", resultMap.get("time_end"));
		payOrderLog.set("result_code", resultMap.get("result_code"));
		payOrderLog.set("sign", resultMap.get("sign"));
		payOrderLog.set("bank_type", resultMap.get("bank_type"));
		payOrderLog.set("nonce_str", resultMap.get("nonce_str"));
		Db.save("fair_pay_log", payOrderLog);
	}
	
	
	public void cancleOrder(int id,String orderNo,long userId) throws ValidateException{
		FairOrder order = FairOrder.dao.findById(id);
		if(order==null){
			throw new ValidateException("当前订单信息不存在");
		}
		if(!order.getStr(FairOrder.ORDER_NO).equals(orderNo) || order.getLong(FairOrder.USER)!=userId){
			throw new ValidateException("当前订单数据信息非本人信息，禁止取消");
		}
		if(order.getInt(FairOrder.STATUS)==FairOrder.STATUS_PAYED){
			throw new ValidateException("当前订单已经支付了 不允许取消");
		}
		order.set(FairOrder.STATUS, FairOrder.STATUS_CANCEL).update();
	}
	
	
	
}
